package com.lagou.watch;


import com.lagou.common.GlobalStatic;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;

public class MyCuratorWatcher implements Runnable {

    private CuratorFramework client;

    public MyCuratorWatcher(CuratorFramework client ) {
        this.client = client;
    }
    public void run() {
        PathChildrenCache cache = new PathChildrenCache(client, "/provide", true);
        try {
            cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
            cache.getListenable().addListener(new PathChildrenCacheListener() {
                public void childEvent(CuratorFramework cf, PathChildrenCacheEvent event) throws Exception {
                    ChildData data = event.getData();
                    if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)){
                        GlobalStatic.servers.put(data.getPath().substring(data.getPath().lastIndexOf("/")+1),new String(data.getData()));
                        System.out.println(data.getPath()+" 加入服务");
                    }else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)){
                        GlobalStatic.servers.remove(data.getPath().substring(data.getPath().lastIndexOf("/")+1));
                        System.out.println(data.getPath()+ "服务失效");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
